# Copyright 2018-2019 ForgeFlow, S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl-3.0).
from datetime import datetime

from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.tools import get_lang


class WorkorderSubcontractingWizard(models.TransientModel):
    _name = "workorder.subcontracting.wizard"
    _description = "Process outsourcing guide"

    line_ids = fields.One2many('workorder.subcontracting.line.wizard', 'parent_id')

    def action_workorder_to_purchase(self):
        partners = {}
        for line in self.line_ids:
            if line.partner_id and line.qty:
                ex_poid = partners.get(line.partner_id.id) or 0
                product = line.workorder_id.workcenter_id.sub_contract_product_tmpl_id
                product_pr_id = self.env['product.product'].sudo().search([('product_tmpl_id', '=', product.id)])
                if not product:
                    raise ValidationError(_('{},Please set up outsourcing service products').format(line.workorder_id.workcenter_id.name))
                if ex_poid == 0:
                    values = {
                        'partner_id': line.partner_id.id,
                        'subcontracting': True,
                        'order_line': [(0, 0, {
                            'product_id': product_pr_id.id,
                            'product_qty': line.qty,
                            'name': "{}，Process outsourcing".format(line.production_id.name),
                            'product_uom': product.uom_id.id,
                            'price_unit': 1,
                            'display_type': False,
                            'date_planned': fields.Datetime.now(),
                            'workorder_id': line.workorder_id.id,
                            's_area': line.area,
                        })]
                    }
                    poid = self.env['purchase.order'].create(values)
                    line.done = True
                    line.purchase_order_id = poid.id
                    partners[line.partner_id.id] = poid.id
                else:
                    self.env['purchase.order.line'].create({
                        'order_id': ex_poid,
                        'product_id': product_pr_id.id,
                        'product_qty': line.qty,
                        'name': "{}，Process outsourcing".format(line.production_id.name),
                        'product_uom': product.uom_id.id,
                        'price_unit': 1,
                        'display_type': False,
                        'date_planned': fields.Datetime.now(),
                        'workorder_id': line.workorder_id.id,
                        's_area': line.area,
                    })
                    line.done = True
                    line.purchase_order_id = ex_poid
            else:
                raise ValidationError(_('{},Please set up outsourcing service products').format(line.partner_id.name))


class WorkorderSubcontractinglineWizard(models.TransientModel):
    _name = "workorder.subcontracting.line.wizard"
    _description = "Process Outsourcing Guide"

    parent_id = fields.Many2one('workorder.subcontracting.wizard', string='Subcontracting Wizard')
    workorder_id = fields.Many2one('mrp.workorder', string='Work Order')
    production_id = fields.Many2one('mrp.production', string='Manufacturing Order',
                                    related='workorder_id.production_id')
    qty_remaining = fields.Float('Remaining Quantity', digits='Product Unit of Measure', related='workorder_id.qty_wip')
    done_qty = fields.Float('Ordered Quantity', digits='Product Unit of Measure', readonly=True)
    partner_id = fields.Many2one('res.partner', string='Vendor')
    qty = fields.Float('Quantity for This Order', digits='Product Unit of Measure')
    done = fields.Boolean("Processed")
    purchase_order_id = fields.Many2one('purchase.order', string='Purchase Order')
    area = fields.Char(string='Area', copy=False, )
